package com.ueboot.weishop.api.controller.weixin;

import com.ueboot.core.http.response.Response;
import com.ueboot.core.utils.HttpClientUtil;
import com.ueboot.weishop.service.weixin.WeiXinService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;


/**
 * Created by yangkui on 2016/12/18.
 * 为微信接口提供服务
 */
@Controller
@RequestMapping(value = "/api/public/wx")
public class WeiXinController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private WeiXinService weiXinService;

    public static final String WX_URL ="http://api.parllay.cn/v1.1/social/wxconfig/7UOHYCCD9T/metadata/get";

    @RequestMapping(value = "/getOpenId",method = RequestMethod.POST)
    @ResponseBody
    public Response<GetOpenIdVo> getOpenId(@RequestBody GetOpenIdVo req) {
        GetOpenIdVo vo = new GetOpenIdVo();
        String openId = weiXinService.getOpenIdByCode(req.getCode(), req.getConfigType());
        vo.setOpenId(openId);
        return new Response<GetOpenIdVo>(vo);
    }

    @RequestMapping(value = "/getAccessToken",method = RequestMethod.POST)
    @ResponseBody
    public Response<GetOpenIdVo> getAccessToken(@RequestBody GetOpenIdVo req) {
        GetOpenIdVo vo = new GetOpenIdVo();
        String accessToken = weiXinService.getAccessToken(req.getConfigType());
        vo.setAccessToken(accessToken);
        return new Response<GetOpenIdVo>(vo);
    }

    @RequestMapping(value = "/getShareInfo",method = RequestMethod.GET)
    @ResponseBody
    public Response<GetOpenIdVo> getShareInfo(@RequestParam String url) {
        logger.info("获取微信分享参数:url:{}",url);
        GetOpenIdVo vo = new GetOpenIdVo();
        String accessToken = weiXinService.getAccessToken("公众号");
        try {
          String   responseBody = HttpClientUtil.get(WX_URL+"?url="+url+"&access_token="+accessToken,30000,30000,"UTF-8");
          if(responseBody!=null){
              responseBody = responseBody.substring(5,responseBody.length());
              responseBody = responseBody.substring(0,responseBody.length()-1);
          }
          vo.setShareInfo(responseBody);
        } catch (IOException e) {
            e.printStackTrace();
        }
        vo.setAccessToken(accessToken);
        return new Response<GetOpenIdVo>(vo);
    }

}
